
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;


class Computer {
public:
    Computer()
    : _brand(nullptr)
    , _price(0)
    { cout << "Computer()" << endl; }

    Computer(const char * brand, double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        cout << "Computer(const char*, double)" << endl;
        strcpy(_brand, brand);
    }

    void setBrand(const char * brand)
    {
        _brand = new char[strlen(brand) + 1]();
        strcpy(_brand, brand);
    }

    void setPrice(double price)
    {   _price = price; }

    void print() 
    {
        if(_brand) {
            cout << "brand:" << _brand << endl;
            cout << "price:" << _price << endl;
        }
    }

    //系统提供的析构函数不再满足需求
    //必须要自定义析构函数
    ~Computer()
    {
        cout << "~Computer()" << endl;
        if(_brand) {
            delete [] _brand;//执行完delete表达式之后，_brand所指的地址没有被修改
            _brand = nullptr;//SAFE DELETE,小习惯
        }
    }

    

private:
    //64位系统默认情况下，按8字节对齐
    char * _brand;
    double _price;
};

Computer gpc1("Thinkpad", 9999);
static Computer gpc2("Thinkpad", 9999);

void test0()
{
    cout << "sizeof(Computer):" << sizeof(Computer) << endl;
    Computer pc;//栈对象
    pc.setBrand("Huawei matebook");
    pc.setPrice(7777);
    pc.print();

    //析构函数可以显式调用
    //pc.~Computer();
    //pc.print();

    Computer * pc3 = new Computer("zhengqiuzhe Y9000", 9998);
    cout << "pc3:";
    pc3->print();
    delete pc3;
    pc3 = nullptr;
}


int main()
{
    test0();
    return 0;
}

